/******************************************************************
*
*	CyberHTTP for Java
*
*	Copyright (C) Satoshi Konno 2002-2003
*
*	File: HTTPServerThread.java
*
*	Revision;
*
*	10/10/03
*		- first revision.
*	
******************************************************************/

package com.cidero.http;

import java.net.*;
import java.io.IOException;
import java.util.logging.Logger;

public class HTTPServerThread extends Thread
{
  private static Logger logger = Logger.getLogger("com.cidero.http");

	private HTTPServer httpServer;
	private Socket sock;
	
  /**
   *  Constructor for dedicated server thread used to process each
   *  incoming HTTP request.
   *
   *  @param  httpServer  Server instance that is the 'parent' of this thread
   *  @param  sock        Socket returned from servers 'accept' routine
   *
   *  TODO: perhaps implement thread pool for efficiency
   */
	
	public HTTPServerThread( HTTPServer httpServer, Socket sock )
	{
		this.httpServer = httpServer;
		this.sock = sock;
	}

	/**
   *  Thread's run method to open a connection and service one or more (in
   *  the case of a persistent connection) incoming HTTP requests
   */
	public void run()
	{
    HTTPConnection connection = null;

    try 
    {
      connection = new HTTPConnection( sock );

      // TODO: Add persistent connection looping logic here
      //  while( connection.stillAlive() ) {
      // 
      //  Get the request from the client, and pass it back up the the 
      //  server. The server will normally respond with an HTTP packet 
      //  of some sort on the same socket
      //
      //  The request content is not retrieved, just the header. The idea
      //  is that the content, if present, is read & parsed in a streaming
      //  manner in the request listener 
      //System.out.println("HTTPServerThread: receiving request hdr");
      HTTPRequest request = connection.receiveRequest( false );

      //System.out.println("HTTPServerThread: performing listener");

      // If listener returns false, another thread has assumed responsiblity
      // for shutting down connection, so set the connection to null here
      if( httpServer.performRequestListener( request ) == false )
      {
        logger.fine("HTTPServerThread: requestListener returned 'false' - no close required");
        connection = null;
      }
      
    }
    catch( IOException e )
    {
      logger.warning("IOException servicing HTTP request");
    }
    finally
    {
      //
      //  Done with this HTTP connection (session) - close it up and 
      //  terminate thread 
      //
      if( connection != null )
      {
        logger.fine("HTTPServerThread: closing connection");
        connection.close();
        connection = null;
      }
    }

    logger.fine("----------HTTPServerThread: Done----------");

	}
}
